﻿using System;
using System.Diagnostics;
using System.Threading.Tasks;
using VideoMergeSplitApp.data;

namespace VideoMergeSplitApp.utils
{
    internal class CmdUtil
    {
        public static string RunFFCmd(string cmd)
        {
            //执行命令 调用程序
            ProcessStartInfo startInfo = new ProcessStartInfo(Constant.FFMPEG_PATH);
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            startInfo.Arguments = cmd;

            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardOutput = true;
            startInfo.CreateNoWindow = true;

            Process process = new Process
            {
                StartInfo = startInfo
            };
            //Process.Start(startInfo);

            process.Start();
            process.WaitForExit(); // 等待命令执行完成

            string output = process.StandardOutput.ReadToEnd(); // 获取命令的输出结果
            return output;
        }


        public static Process RunFFPlayCmd(string cmd)
        {
            //执行命令 调用程序
            ProcessStartInfo startInfo = new ProcessStartInfo(Constant.FFPLAY_PATH)
            {
                //  startInfo.WindowStyle = ProcessWindowStyle.Minimized;
                Arguments = cmd,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            };

            Process process = new Process
            {
                StartInfo = startInfo
            };
            process.Start();
    
            return process;
        }






        public static Task<string> RunCommandAsync(string command)
        {
            var tcs = new TaskCompletionSource<string>();

            try
            {
                Process process = new Process();
                process.StartInfo.FileName = "cmd.exe";
                process.StartInfo.Arguments = "/c " + command;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.CreateNoWindow = true;

                process.OutputDataReceived += (sender, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        tcs.TrySetResult(e.Data);
                    }
                };

                process.EnableRaisingEvents = true;
                process.Exited += (sender, e) =>
                {
                    tcs.TrySetResult(null);
                    process.Dispose();
                };

                process.Start();
                process.BeginOutputReadLine();
            }
            catch (Exception ex)
            {
                tcs.TrySetException(ex);
            }

            return tcs.Task;
        }

    }
}
